package router

import (
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"github.com/teambition/gear"
)

// WwwHandler 注册静态站点服务
func WwwHandler(root string, excludeRouters ...string) gear.Middleware {
	return func(ctx *gear.Context) error {
		if !(ctx.Method == http.MethodGet || ctx.Method == http.MethodHead) {
			return nil
		}

		path := ctx.Path
		for _, r := range excludeRouters {
			if strings.HasPrefix(path, r) {
				return nil
			}
		}

		fpath := filepath.Join(root, filepath.FromSlash(path))
		_, verr := os.Stat(fpath)
		if verr != nil && os.IsNotExist(verr) {
			http.ServeFile(ctx.Res, ctx.Req, filepath.Join(root, "index.html"))
			return nil
		}

		http.ServeFile(ctx.Res, ctx.Req, fpath)
		return nil
	}
}
